package com.zhangchuchu.neohealth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangchuchu.neohealth.entity.Goods;
import com.zhangchuchu.neohealth.entity.UserProfile;
import com.zhangchuchu.neohealth.mapper.GoodsMapper;
import com.zhangchuchu.neohealth.mapper.UserProfileMapper;
import com.zhangchuchu.neohealth.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    private UserProfileMapper userProfileMapper;

    @Override
    @Transactional
    public void exchangeGoods(Integer userId, Integer goodsId) {
        // 1. 获取商品信息
        Goods goods = baseMapper.selectById(goodsId);
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }

        // 2. 获取用户信息
        UserProfile user = userProfileMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 3. 校验积分是否足够
        if (user.getIntegral() < goods.getPoints()) {
            throw new RuntimeException("积分不足，无法兑换");
        }

        // 4. 校验库存是否足够
        if (goods.getQuantity() <= 0) {
            throw new RuntimeException("商品库存不足");
        }

        // 5. 更新积分和库存
        int newIntegral = user.getIntegral() - goods.getPoints();
        int newQuantity = goods.getQuantity() - 1;

        // 6. 更新数据库
        user.setIntegral(newIntegral);
        goods.setQuantity(newQuantity);

        userProfileMapper.updateById(user);
        baseMapper.updateById(goods);
    }
}
